<template>
  <Title>
    <template v-slot:center>用户登录</template>
  </Title>
  <div id="register">
    <h1>图书商城</h1>
    <van-form @submit="onSubmit">
      <van-field
          v-model="email"
          name="邮箱"
          label="邮箱"
          placeholder="请输入正确邮箱格式"
          :rules="[{ required: true, message: '请填写正确邮箱' }]"
      />
      <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />

      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" color="#42b983">
          登录
        </van-button>
      </div>
    </van-form>
    <div class="link-login" @click="$router.push({path:'/register'})">没有账号，立即注册</div>
  </div>
</template>

<script>
import Title from "../../components/common/title/Title";
import {reactive, ref, toRefs} from "vue";

import {Notify,Toast} from 'vant'
import {useRouter} from 'vue-router'
import {login} from "../../network/user";
import {useStore} from 'vuex'
export default {
  components:{Title},
  setup(){
    const router=useRouter()
    const store=useStore()
    const userinfo=reactive({
      email:'',
      password:'',

    })
    const onSubmit=()=>{
      login(userinfo).then(res=>{
        console.log(1)
        //将token保存在本地
        window.localStorage.setItem('token',res.access_token)
        store.commit('setIsLogin',true)
        Toast.success('登录成功')
        userinfo.email='';
        userinfo.password='';
        setTimeout(()=>{
          router.go(-1)
        },500)
      })
    }
    return{...toRefs(userinfo),onSubmit}
  }
}
</script>

<style scoped lang="scss">
#register{
  padding: 45px 0 50px;
  h1{
    text-align: center;
  }
  .link-login{
    text-align: center;
  }
}
</style>